

import { AppDataSource } from '@/config/AppDataSource';
import { CreateBannerDto, UpdateBannerDto, QueryBannerDto, DeleteBannerDto, SortBannerDto } from '@/dto/banner.dto';
import { Banner } from '@/entities/banner.entity';
import { In } from 'typeorm';
export class BannerRepository {
    private repositor = AppDataSource.getRepository(Banner);
    constructor() { }

    async findExcludeId(data: UpdateBannerDto) {
        const conflictCategory = await this.repositor
            .createQueryBuilder('banner')
            .where('banner.id != :id', { id: data.id })
            .andWhere('(banner.title = :title)', { title: data.title })
            .getOne();
        return conflictCategory
    }


    async bannerExists(title: string) {
        const c = await this.repositor.findOne({
            where: [
                { title },
            ],
        });
        return c;
    }

    async findById(id: number) {

        const item = await this.repositor.findOneBy({
            id
        })
        return item;
    }

    async create(data: CreateBannerDto): Promise<Banner> {
        const banner = new Banner();

        banner.status = data.status;
        banner.comment = data.comment;
        banner.title = data.title;
        banner.imageUrl = data.imageUrl;
        banner.linkUrl = data.linkUrl;
        banner.sortOrder = data.sortOrder;
        banner.isActive = data.isActive;

        const result = await this.repositor.save(banner)
        // console.log("result", result)
        return result;
    }
    async update(data: UpdateBannerDto) {
        const banner = new Banner();
        banner.id = data.id;

        banner.status = data.status;
        banner.comment = data.comment;
        banner.title = data.title;
        banner.imageUrl = data.imageUrl;
        banner.linkUrl = data.linkUrl;
        banner.sortOrder = data.sortOrder;
        banner.isActive = data.isActive;

        return this.repositor.save(banner);

    }



    async selectList(reqData: QueryBannerDto) {
        const { page, pageSize, title, orderBy, comment, status, fromDate, toDate } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('banner')
            .select([

                'banner.id',
                'banner.createdAt',
                'banner.updatedAt',


                'banner.status',
                'banner.comment',
                'banner.title',
                'banner.imageUrl',
                'banner.linkUrl',
                'banner.sortOrder',
                'banner.isActive',

            ]);

        if (title) {
            queryBuilder.andWhere('banner.title LIKE :title', { title: `%${title}%` });
        }
        if (comment) {
            queryBuilder.andWhere('banner.comment LIKE :comment', { comment: `%${comment}%` });
        }
        if (status) {
            queryBuilder.andWhere('banner.status = :status', { status });
        }
        // 添加创建日期范围查询
        if (fromDate && toDate) {
            queryBuilder.andWhere('banner.createdAt BETWEEN :fromDate AND :toDate', {
                fromDate: new Date(fromDate),
                toDate: new Date(`${toDate}T23:59:59.999Z`)
            });
        } else if (fromDate) {
            queryBuilder.andWhere('banner.createdAt >= :fromDate', {
                fromDate: new Date(fromDate)
            });
        } else if (toDate) {
            queryBuilder.andWhere('banner.createdAt <= :toDate', {
                toDate: new Date(`${toDate}T23:59:59.999Z`)
            });
        }

        const [sortBy, sortOrder] = orderBy.split(" ")
        const [banner, total] = await queryBuilder
            .orderBy(`banner.${sortBy}`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
        return {
            list: banner,
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: DeleteBannerDto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }
    async sort(reqData: SortBannerDto) {
        const res = await this.repositor.createQueryBuilder('banner')
            .update()
            .set({
                sortOrder: () => 'CASE ' +
                    reqData.list.map(item => `WHEN id = '${item.id}' THEN ${item.sortOrder} `).join('') +
                    'ELSE sortOrder END'
            })
            .whereInIds(reqData.list.map(item => item.id))
            .execute();


    }
}

export default new BannerRepository();

